package wta.mongo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FilenameFilter;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.WriteResult;

/**
 * 更新用户的体检问答题信息
 * @author icyfox
 *
 */
public class UpdateUserQuestion {

	private static Mongo mongo;
	private static DB db;
	private static DBCollection coll;

	public static void main(String[] args) throws Exception {
		
		mongo = new Mongo("10.110.150.158");
		
		db = mongo.getDB("china");
		coll = db.getCollection("users");
		
		File dic  = new File("D:\\Now\\ciming\\慈铭数据.20150428\\02");
		String[] list = dic.list(new FilenameFilter() {
			
			@Override
			public boolean accept(File dir, String name) {
				return name.contains("02问卷调查");
			}
		});
		
		for (String string : list) {
			System.out.println(string);
			insert(dic.getAbsolutePath() +'\\'+ string);
		}
		
		mongo.close();
	}

	private static void insert(String file) throws Exception {
		System.out.println("开始插入文件："+file);
		BufferedReader br = new BufferedReader(new FileReader(file));
		String curID = null;
		BasicDBObject toModify = null;
		
		while (true) {
			String line = br.readLine();
			if (line == null) {
				BasicDBObject toFind = new BasicDBObject();
				toFind.put("uid", curID);
				DBObject obj = coll.findOne(toFind);
				if (obj == null)
					System.err.println(curID + " not found");
				else{
					WriteResult re = coll.update(obj, new BasicDBObject("$set", toModify), true, false);
					//System.out.println(curID);
				}
				break;
			}
			if (line.contains("以上疾病治疗情况及现状")) continue;
			String[] info = line.split(" ");
		 	
			if (curID == null){
				curID = info[0];
				toModify = new BasicDBObject();
				toModify.put(info[2], info[4]);
			}else if (!curID.equals(info[0])) {
				BasicDBObject toFind = new BasicDBObject();
				toFind.put("uid", curID);
				
				DBObject obj = coll.findOne(toFind);
				if (obj == null)
					System.err.println(info[0] + " not found");
				else{
					WriteResult re = coll.update(obj, new BasicDBObject("$set", toModify), true, false);
					//System.out.println(curID);
				}
				
				toModify = new BasicDBObject();
				toModify.put(info[2], info[4]);
				curID = info[0];
			}else {
				toModify.put(info[2], info[4]);
			}
		}
		
		br.close();
	}
	
}
